<?php

namespace app\m\controller;

use think\Db;

class Xzb
{

    public function pic_upload()
    {
        session('ses',['uid'=>2,'oid'=>2]);
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $oid = $ses['oid'];
        $uid = $ses['uid'];
        $type = isset($_GET['type']) ? intval($_GET['type']) : 1;
        $now = $_SERVER['REQUEST_TIME'];
        $err = $_FILES['file']['error'];
        $file = request()->file('file');

        if ($err) {
            echo '{"err":2,"msg":"上传失败"}';
            $ip = $_SERVER['REMOTE_ADDR'];
            $json = ['err' => 2, 'msg' => '上传失败', 'time' => date('Y-m-d H:i:s', $now), 'file' => $_FILES];
            loger('vod    ' . $ip, 'xzb');
        }
        //$vodpath = ROOT_PATH.'app'.DS.'xzb'.DS.'vod';
        $picpath = ROOT_PATH . 'm' . DS . 'xzb' . DS . 'uploads' . DS .'pics';
        $path='https://x.g56.cn/xzb/uploads/pics/';
        $info = $file->validate(['ext' => 'jpg,png,gif'])->move($picpath);
        if ($info) {
            // 成功上传后 获取上传信息
            // 输出 上=>传文件名
            $saveName = $info->getSaveName();
            if (strpos($saveName, '\\')) {
                $saveName = str_replace('\\', '/', $saveName);
            }
            // 成功上传后 获取上传信息

            $pic_path = $path . $saveName;// 线上环境 图片上传地址
            $p = strrpos($saveName, '.');
            $thumbName = substr($saveName, 0, $p) . '_thumb.png'; // 缩略图
            $thumbPath = $picpath . DS . $thumbName;
      
            list($width, $height, $picType, $attr) = getimagesize($pic_path);
            // 产生缩略图
            $im = img_create($pic_path, $picType);
            $images = imagecreatetruecolor(200, 200);
            imagecopyresampled($images, $im, 0, 0, 0, 0, 200, 200, $width, $height);
            imagepng($images,$thumbPath);
            imagedestroy($images);
            $thumb_path = $path . $thumbName;

            $data = ['type' => $type, 'pic' => $pic_path, 'thumb' => $thumb_path, 'time' => $now, 'uid' => $uid];
            if ($type == 1) {
                $id = Db::table('x1_activity_img')->insertGetId($data);
                $data['id'] = $id;
                echo json_encode(['err' => 0, 'msg' => '上传成功', 'pic' => $data]);
            }

        } else {
            echo '{"err":"1001","msg":"上传失败"}';
        }
    }



    public function vod_upload()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $oid = $ses['oid'];
        $uid = $ses['uid'];
        $type = isset($_GET['type']) ? intval($_GET['type']) : 10;
        $now = $_SERVER['REQUEST_TIME'];
        $err = $_FILES[0]['error'];
        $file = request()->file('file');

        if ($err) {
            echo '{"err":2,"msg":"上传失败"}';
            $ip = $_SERVER['REMOTE_ADDR'];
            $json = ['err' => 2, 'msg' => '上传失败', 'time' => date('Y-m-d H:i:s', $now), 'file' => $_FILES];
            loger('vod    ' . $ip, 'xzb');
        }

        //$vodpath = ROOT_PATH.'app'.DS.'xzb'.DS.'vod';
        $vodpath = ROOT_PATH . 'app' . DS . 'xzb' . DS . 'vods';
        $info = $file->validate(['ext' => 'mp4', 'rm', 'flv', 'avi', 'mov', 'amv'])->move($vodpath);
        if ($info) {
            // 成功上传后 获取上传信息
            // 输出 上传文件名
            $saveName = $info->getSaveName();
            if (strpos($saveName, '\\')) {
                $saveName = str_replace('\\', '/', $saveName);
            }
            // 成功上传后 获取上传信息
            // $thumb_path = 'http://192.168.0.5/uploads/doubility/' . $saveName;// 本地测试环境 图片上传地址
            $thumb_path = 'http://app.yaosports.com/xzb/vods/' . $saveName;// 线上环境 图片上传地址
            // list($width, $height, $picType, $attr) = getimagesize($path . DS . $saveName);
            // 产生缩略图
            $zoom_pic = 'http://app.yaosports.com/img/video_default_cover.jpg';
            $data = ['type' => $type, 'pic' => $thumb_path, 'thumb' => $zoom_pic, 'upload_time' => $now, 'upload_user' => $uid];

        } else {
            echo '{"err":"1001","msg":"上传失败"}';
        }
    }


    //广场动态添加/修改
    public function add_activity(){
        $ses=session('ses');
        if(!$ses){
            echo '{"err":"1","msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $title = isset($_GET['title']) ? addslashes($_GET['title']) : '';
        $content = isset($_GET['content']) ? addslashes($_GET['content']) : '';
        $pics = isset($_GET['pics']) ? addslashes($_GET['pics']) : '';
        $now=$_SERVER['REQUEST_TIME'];
        if($id){
            $qs=Db::query(' select a.id,r.uid from x1_activity a left join x1_user_role r on a.rid=r.id where a.id=? and state=1',[$id]);
            if(!$qs){
                echo '{"err":1002,"msg":"动态信息不存在"}';
                return;
            }
            if($qs[0]['uid']!=$uid){
                echo '{"err":1003,"msg":"您不是该信息上传者，无法修改"}';
                return;
            }
            Db::table('x1_activity')->where('id',$id)->update(['title'=>$title,'content'=>$content,'time'=>$now]);
            Db::execute('update x1_activity_img set pid=? where id in ('.$pics.')',$id);
        }else{
           $qs=Db::query('select id,uid,type,pid from x1_user_role where uid=? and type in (2,3) and state=1',[$uid]);
           if(!$qs){
               echo '{"err":1001,"msg":"校长或教师可以上传动态"}';
               return;
           }
           $rid=$qs[0]['id'];

           $id=Db::table('x1_activity')->insertGetId(['rid'=>$rid,'title'=>$title,'content'=>$content,'time'=>$now,'likes'=>0,'is_rec'=>0,'state'=>0]);
            Db::execute('update x1_activity_img set pid=? where id in ('.$pics.')',[$id]);
        }
        echo '{"err":0,"msg":"编辑成功"}';
    }


    public function sms_verify()
    {
        $code = $_GET['sms_code']; // 手机验证码
        $phone = $_GET['phone'];
        // 验证验证码
        $valid = 0; // 手机验证码通过检查
        $now = $_SERVER['REQUEST_TIME'];
        $cid = session('sms');
        // 有效期5分钟 5*60
        if ($cid > 0 && ($qs = Db::query('select phone, code, time, verify from x1_sms where id = ?', [$cid]))) {
            $cr = $qs[0];
            if (($now - $cr['time']) > 1000) { // 验证码已过期
                return '{"err":3,"msg":"验证码已过期"}';
            }
            $verify = $cr['verify'];
            if ($cr['verify'] > 200) { // 已经成功验证
                $valid = 1;
            } else if ($verify > 30) {
                return '{"err":3,"msg":"验证码已失效"}';
            } else if ($cr['code'] == $code) {
                if ($cr['verify'] < 200) { // 更新验证成功时间
                    Db::execute('update x1_sms set verify = ? where id = ?', [$now, $cid]);
                }
                $valid = 1;
            } else {
                // 更新验证次数
                Db::execute('update x1_sms set verify = verify + 1 where id = ?', [$cid]);
            }
        }
        if (!$valid) {
            return '{"err":1,"msg":"验证码错误"}';
        }
        return '{"err":0,"msg":"验证成功","phone":"' . $phone . '"}';
    }

    //name 姓名
    //duty 职务
    //pid 主体id
    //type 1 校足办，2校长，3教师
    //area  区域code (一般校足办选择)
    //phone 电话
    //sms_code 验证码
    public function add_apply()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"登录信息失效"}';
            return;
        }
        $oid = $ses['oid'];
        $uid = $ses['uid'];
        $res = $this->sms_verify();
        $result = json_decode($res, true);
        if ($result['err'] != 0) {
            echo $res;
            return;
        }
        $phone = $result['phone'];
        $name = trim($_GET['name']);
        $duty = isset($_GET['duty']) ? addslashes(trim($_GET['duty'])) : '';
        $pid = isset($_GET['pid']) ? intval($_GET['pid']) : 0;
        $type = intval($_GET['type']);
        $area = isset($_GET['area']) ? intval($_GET['area']) : 0;
        if (!$name && !$duty && !$phone) {
            echo '{"err":1001,"msg":"param error"}';
            return;
        }
        if ($type == 1) {
            //校足办认证，根据区域code获取校足办id或者添加校足办
            if (!$pid) {
                $qs = Db::query('select id from x1_unit where area=?', [$area]);
                if (!$qs) {
                    $qs = Db::query('select name,shortname from area where code=?', [$area]);
                    if (!$qs) {
                        echo '{"err": "1001","msg": "没有查到此区域"}';
                        return;
                    }
                    $unit = $qs[0]['name'];
                    $shortname = $qs[0]['shortname'];
                    $unit_type = 1;
                    if ($area % 10000) {
                        $unit_type = 3;
                    } elseif ($area % 100) {
                        $unit_type = 2;
                    }
                    $data = ['name' => $unit . '校园足球工作领导小组', 'shortname' => $shortname . '校足办', 'area' => $area, 'address' => '', 'type' => $unit_type];
                    $pid = Db::table('x1_unit')->insertGetId($data);
                } else {
                    $pid = $qs[0]['id'];
                }
            }

        } else {
            //校长或教师认证
            if ($type == 2 && !$duty) {
                $duty = '校长';
            }
            $qs = Db::query('select area from x1_school where id=?', [$pid]);
            if (!$qs) {

                echo '{"err":1002,"msg":"该学校不存在"}';
                return;
            }
            $area = $qs[0]['area'];
        }
        $now = $_SERVER['REQUEST_TIME'];
        $data = ['uid' => $uid, 'pid' => $pid, 'type' => $type, 'name' => $name, 'duty' => $duty, 'area' => $area, 'msg' => '', 'result' => 0, 'time' => $now, 'ack_id' => '', 'ack_time' => 0];
        $id = Db::table('x1_role_apply')->insertGetId($data);

        $user = Db::query('select name,phone from x1_user where uid=?', [$uid]);
        if ($user && !($user[0]['name'] && $user[0]['phone'])) {
            Db::execute('update x1_user set name=?,phone=? where uid=?', [$name, $phone, $uid]);
        }
        echo json_encode(['err' => 0, 'msg' => '申请成功，正在等待审核中', 'id' => $id, 'phone' => $phone]);
        return;
    }




    //user     用户的name,phone
    //identity  user_school表中的所有身份信息，每一条都有id,pid(主体id),duty,type,cb_name(主体名称)
    //获取用户信息和所有身份
    public function user_info()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"身份信息失效"}';
            return;
        }
        $uid = $ses['uid'];
        $user = Db::query('select name,phone from x1_user where uid=?', [$uid]);
        $qs = Db::query('select us.id,us.pid,us.duty,us.type,s.school_name,g.name gov_name from x1_user_school us left join x1_school s on us.pid=s.id left join x1_govment g on us.pid=g.id where us.uid=?', [$uid]);
        $identity = $qs;
        foreach ($identity as $k => $v) {
            if ($v['type'] == 1) {
                $identity[$k]['cb_name'] = $v['school_name'];
            } else {
                $identity[$k]['cb_name'] = $v['gov_name'];
            }
            unset($identity[$k]['school_name']);
            unset($identity[$k]['gov_name']);
        }
        echo json_encode(['err' => 0, 'user' => $user, 'identity' => $identity]);
    }



    //用户身份验证申请列表
    //type   0 未审核，1 已审核
    public function user_apply_list()
    {
        //$sort = isset($_GET['sort']) ? addslashes($_GET['sort']) : '';
        $type = isset($_GET['type']) ? $_GET['type'] : 0;
        $m = isset($_GET['m']) ? intval($_GET['m']) : 0;
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $num = 20;
        $user = session('ses');
        if (!$user) {
            echo '{"err":1,"msg":"身份信息失效"}';
            return;
        }
        $uid = $user['uid'];
        $qs = Db::query('select r.pid,r.type,r.duty,n.area,area.pc from x1_user_role r left join x1_unit n on r.pid=n.id left join area on n.area=area.code where r.uid=? and r.state=1', [$uid]);
        $users=$qs;
        $list=[];
        if($users){
            $where=[];
            $where1='';
            foreach($users as $v){
                //省级 取同级和市级，市级 取区级，区级 取校长，校长 取教师
                if($v['type']==1 && $v['pc']==0){
                    $where[]="(a.type=1 and (area.pc='{$v['area']}' or a.area='{$v['area']}'))";
                }elseif($v['type']==1 && $v['code']){
                    $where[]="(a.type=1 and area.pc='{$v['area']}')";
                }elseif($v['type']==1){
                    $where[]="(a.type=2 and a.area='{$v['area']}')";
                }elseif($v['type']==2){
                    $where[]="(a.type=3 and a.pid='{$v['pid']}')";
                }
            }
            $where=array_unique($where);

            if($id && $m){
                $where1="id > $id  and ";
            }
            $list=Db::query('select a.id,a.pid,a.uid,a.name,a.duty,a.result,a.msg,a.time,a.type,a.area from x1_role_apply a left join area on a.area=area.code where '.$where1.join(' or ',$where).'order by id desc');
        }

        

        $check = [0 => '未审核', '2' => '审核通过', 3 => '已拒绝', 6 => '已撤回'];
        foreach ($list as $k => $v) {
            $list[$k]['time'] = date('Y-m-d H:i', $v['time']);
            $list[$k]['check'] = $check[$v['result']];
        }
        echo json_encode(["err" => 0, "msg" => "获取成功", "list" => $list]);
    }

    //审核用户身份申请详情
    public function user_apply_detail()
    {
        $user = session('ses');
        if (!$user) {
            echo '{"err":1,"msg":"登录状态失效"}';
            return;
        }
        $uid = $user['uid'];
        $qs = Db::query('select a.id,a.name,a.duty,a.pid,a.type,a.area,a.result,a.msg,a.time,u.phone,s.name school_name,n.name unit_name from x1_role_apply a left join x1_school s on a.pid=s.id left join x1_unit n on a.pid=n.id left join x1_user u on a.uid=u.uid  where a.uid=?', [$uid]);
        if (!$qs) {
            echo json_encode(['err' => 0, 'msg' => '未申请', 'apply' => []]);
            return;
        }
        $apply = $qs[0];
        $list = [];
        $apply['pname'] = $apply['type'] == 1 ? $apply['unit_name'] : $apply['school_name'];
        unset($apply['unit_name']);
        unset($apply['school_name']);
        echo json_encode(['err' => 0, 'msg' => '已申请', 'apply' => $apply]);
    }

    //点赞/取消点赞操作
    public function add_likes()
    {
        $ses = session('ses');
        $rev = ['err' => 0, 'msg' => '操作成功'];
        if (!$ses) {
            echo '{"err":1,"msg":"登录状态失效"}';
            return;
        }
        $uid = $ses['uid'];
        if (!$uid) {
            echo '{"err":1001,"msg":"请先进行身份认证"}';
            return;
        }
        $id = intval($_GET['id']);
        $state = intval($_GET['state']);
        $qs=Db::query('select name from x1_user where uid=?',[$uid]);
        $name=$qs?$qs[0]['name']:'';
        if (!$id) {
            echo '{"err":1002,"msg":"param error"}';
            return;
        }
        $qs=Db::query('select id from x1_user_role where uid=?',[$uid]);
        if(!$qs){
            echo '{"err":1003,"msg":"身份认证通过后才能点赞"}';
            return;
        }

        $qs = Db::query('select * from x1_likes where uid=? and pid=?', [$uid, $id]);
        if ($qs) {
            $likes_id = $qs[0]['id'];
            if ($state == 1) {
                Db::query('update x1_likes set state=? where id=?', [$state, $likes_id]);
                echo '{"err":0,"msg":"点赞成功","state":1,"name":"'.$name.'"}';
            } else {
                Db::query('update x1_likes set state=? where id=?', [$state, $likes_id]);
                echo '{"err":0,"msg":"取消成功","state":0,"name":"'.$name.'"}';
            }
        } else {
            if ($state == 1) {
                $res = Db::table('x1_likes')->insertGetId(['uid' => $uid, 'pid' => $id, 'state' => $state]);
                echo '{"err":0,"msg":"点赞成功","state":1,"name":"'.$name.'"}';
            } else {
                echo '{"err":0,"msg":"取消成功","state":0,"name":"'.$name.'"}';
            }
        }
    }


    //id   user_apply主键id
    public function apply_detail()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"登录状态失效"}';
            return;
        }
        $uid = $ses['uid'];
        $id = intval($_GET['id']);

        $qs = Db::query('select id,pid,uid,area,name,duty,type,result,msg,time from x1_role_apply where id=? ', [$id]);

        if (!$qs) {
            echo json_encode(['err' => 1001, 'msg' => '申请信息不存在', 'apply' => [], 'list' => []]);
            return;
        }
        $apply = $qs[0];
        $type = $apply['type'];
        $pname = '';
        if ($type == 1) {
            $qs = Db::query('select name from x1_unit where id=?', [$apply['pid']]);
            $pname = $qs ? $qs[0]['name'] : '';
        } else {
            $qs = Db::query('select name from x1_school where id=?', [$apply['pid']]);
            $pname = $qs ? $qs[0]['name'] : '';
        }
        $qs = Db::query('select phone from x1_user where uid=?', [$apply['uid']]);
        $phone = $qs ? $qs[0]['phone'] : '';
        $apply['pname'] = $pname;
        $apply['phone'] = $phone;
        $apply['time_format'] = date('Y-m-d H:i', $apply['time']);

        //apply  id,pid,uid,area,name,duty,type,result,msg,pname,time(格式化过后)
        echo json_encode(['err' => 0, 'msg' => '获取申请信息成功', 'apply' => $apply]);
    }


    //keywords  关键字
    //longitude 经度
    //latitude  纬度
    public function search_school()
    {
        $user = session('ses');
        if (!$user) {
            echo '{"err":1,"msg":"登录状态失效"}';
            return;
        }
        $uid = $user['uid'];

        $keywords = isset($_GET['keywords']) ? addslashes($_GET['keywords']) : '';
        $lng = isset($_GET['longitude']) ? $_GET['longitude'] : 0;
        $lat = isset($_GET['latitude']) ? $_GET['latitude'] : 0;


        if ($keywords) {
            $list = Db::table('x1_school')->where('name', 'like', ':name')->bind(['name' => "%{$keywords}%"])->limit(0, 100)->select();
        } else {
            //通过经纬度查询2千米以内的
            $distance = 2;  //距自己距离，千米
            $earth_radius = 6371; //地球半径，千米
            $dlng = 2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
            $dlng = rad2deg($dlng);
            $dlat = $distance / $earth_radius;
            $dlat = rad2deg($dlat);
            $max_lat = $lat + $dlat;
            $min_lat = $lat - $dlat;
            $max_lng = $lng + $dlng;
            $min_lng = $lng - $dlng;

            $qs = Db::query('select id,name,address,lat,lng from x1_school where lat>? and lat<? and lng>? and lng<? limit 0,20', [$min_lat, $max_lat, $min_lng, $max_lng]);

            $list = $qs;

        }


        echo json_encode(['err' => 0, 'msg' => '获取学校成功', 'list' => $list]);
    }


    public function search_area()
    {
        $user = session('ses');
        if (!$user) {
            echo '{"err":1,"msg":"登录状态失效"}';
            return;
        }
        $uid = $user['uid'];
        $code = isset($_GET['code']) ? intval($_GET['code']) : 0;
        $pc = floor($code / 100);
        $list = Db::table('area')->field('code,name,shortname')->where('pc', $pc)->limit(0, 100)->select();

        echo json_encode(['err' => 0, 'msg' => '获取地区', 'list' => $list]);
    }


    public function add_message()
    {

    }

    public function get_message()
    {

    }

    public function message_detail()
    {

    }


    public function my_activity_list()
    {
        $ses = session('ses');
        $uid = $ses['uid'];
        $m = isset($_GET['m']) ? intval($_GET['m']) : 0; //0刷新 ，1加载
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $more = $m && $id;
        $qs = Db::table('x1_activity a')->field('a.id,ur.uid,a.time,a.title,a.content,a.likes,u.name,ur.duty,ur.pid,u.avatar,IFNULL(s.name,"") pname')->join('x1_user_role ur', 'a.rid=ur.id', 'LEFT')->join('x1_user u', 'ur.uid=u.uid', 'LEFT')->join('x1_school s', 'ur.pid=s.id', 'LEFT')->where('a.state=0')->where('u.uid', $uid)->order('a.id desc');
        if ($more) {
            $qs = $qs->where('a.id', 'lt', $id);
        }
        $qs = $qs->limit(0, 5)->select();
        $ids = [];
        $activity = [];
        foreach ($qs as $k => $v) {
            $v['name'] = $v['name'] ? $v['name'] : '';
            $v['content'] = strlen($v['content']) > 40 ? substr($v['content'], 0, 40) . '..' : $v['content'];
            $v['time'] = date('m-d H:i', $v['time']);
            $v['avatar'] = $v['avatar'] ? $v['avatar'] : 'https://c.g56.cn/x9/user_im.png';
            $v['commit'] = 0;
            $v['likes'] = 0;
            $activity[$v['id']] = $v;
            $ids[] = $v['id'];
        }

        if ($ids) {
            //评论
            $commit = Db::query('select count(*) num,c.pid from x1_commit c left join x1_user u on c.uid=u.uid where c.pid in (' . join(',', $ids) . ')  and c.state < 3 group by c.pid');
            foreach ($commit as $com) {
                $activity[$com['pid']]['commit'] = $com['num'];
            }
            //点赞
            $likes = Db::query('select count(*) num,pid from x1_likes where pid in (' . join(',', $ids) . ') and state=1 group by pid');

            foreach ($likes as $like) {
                $activity[$like['pid']]['likes'] = $like['num'];
            }
            $activity = array_values($activity);
        }
        $qs=Db::query('select name from x1_user where uid=?',[$uid]);

        echo json_encode(['err' => 0, 'msg' => '获取动态成功', 'list' => $activity]);
    }

    public function activity_detail()
    {
        $ses = session('ses');
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$ses || !$id) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $qs = Db::query('select id,title,content,time from x1_activity where id=?', [$id]);
        if (!$qs) {
            echo '{"err":"1001","msg":"动态信息不存在"}';
            return;
        }
        $activity = $qs[0];
        $activity['time'] = date('m-d H:i', $activity['time']);
        $commit = Db::query('select c.id,c.uid,c.content,c.time,u.name,u.avatar from x1_commit c left join x1_user u on c.uid=u.uid where c.pid=? and c.state=0', [$id]);
        $activity['commit'] = $commit ? $commit : [];
        $qs = Db::query('select count(*) as num from x1_likes where pid=?', [$id]);
        $activity['likes'] = $qs[0]['num'];
        $activity['pics'] = Db::query('select id,uid,pid,thumb,pic from x1_activity_img where pid=? and state!=6 and type=1', [$id]);
        echo json_encode(['err' => '0', 'msg' => '获取动态详情成功', 'activity' => $activity]);
    }

    public function add_commit()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"登录状态失效"}';
            return;
        }
        $uid = $ses['uid'];

        if (!$uid) {
            echo '{"err":2,"msg":"请前往\"我的\"进行身份认证,认证通过后可以发表评论"}';
            return;
        }

        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $content = isset($_GET['content']) ? addslashes($_GET['content']) : '';
        if (!$id || !$content) {
            echo '{"err":3,"msg":"评论失败，请重新评论"}';
            return;
        }

        $max_commit = 100;  //限制同一名用户对一条信息最多评论100次
        $count = Db::table('x1_commit')->where('uid', $uid)->where('pid', $id)->count();
        if ($count >= $max_commit) {
            echo '{"err":1001,"msg":"你对该条动态的评论已达到' . $max_commit . '条，无法再次评论。"}';
            return;
        }
        $qs = Db::query('select uid,name from x1_user  where uid=?', [$uid]);
        if (!$qs) {
            echo '{"err":1002,"msg":"用户信息不存在"}';
            return;
        }
        $user = $qs[0];
        $name = $user['name'];

        $qs = Db::query('select id from x1_user_role where uid=? and state=1', [$uid]);
        if (!$qs) {
            echo '{"err":"1003","msg":"请先进行身份认证,认证通过后可以留言"}';
            return;
        }
        $err_words = []; //词语过滤，暂时未开启
        $rule = 1;       //1 显示这条评论  0不显示
        $ip = $_SERVER['REMOTE_ADDR'];
        $now = $_SERVER['REQUEST_TIME'];
        $data = ['uid' => $uid, 'pid' => $id, 'name' => $name, 'content' => $content, 'ip' => $ip, 'time' => $now, 'state' => 0];
        $commit_id = Db::table('x1_commit')->insertGetId($data);
        if (!$commit_id) {
            echo '{"err":1002,"msg":"评论失败"}';
            return;
        }
        $data['id'] = $commit_id;
        echo json_encode(['err' => 0, 'msg' => '评论成功', 'commit' => $data, 'rule' => $rule]);
    }

    public function my_duty()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"登录状态失效"}';
            return;
        }
        $uid = $ses['uid'];
        $m = isset($_GET['m']) ? intval($_GET['m']) : 0;
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $qs = Db::query('select * from x1_user u left join x1_user_role r on u.uid=r.uid where u.uid=? and r.type in (2,3) and r.state=1', [$uid]);
        if (!$qs) {
            echo '{"err"：1001,"msg":"您没有校园用户身份，请前去\"我的\"进行认证"}';
            return;
        }
        $user = $qs[0];
        $where = '';
        if ($m && $id) {
            $where = ' and id < ' . $id;
        }
        $policy = Db::query('select id,title,content,is_achieve,year,ask_num,ach_num,type from x1_aim where pid=? ' . $where . ' order by time desc', [$user['pid']]);
        echo json_encode(['err' => 0, 'msg' => '获取学校政策成功', 'list' => $policy]);
    }

    public function del_activity_pic()
    {
        $ses = session('ses');
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$ses || !$id) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $qs = Db::query('select id,uid from x1_activity_img where id=?', [$id]);
        if (!$qs) {
            echo '{"err":1001,"msg":"图片信息不存在"}';
            return;
        }
        if ($qs[0]['uid'] != $uid) {
            echo '{"err":1002,"msg":"这张照片不是您上传的，无法删除"}';
            return;
        }
        Db::execute('update x1_activity_img set state=6 where id=?', [$id]);
        echo '{"err":"0","msg":"删除成功"}';
    }

    //查找联系人
    public function search_concact(){
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid=$ses['uid'];
        $keywords=isset($_GET['keywords'])?addslashes(trim($_GET['keywords'])):'';
        $id=isset($_GET['id'])?intval($_GET['id']):0;
        $m=isset($_GET['m'])?intval($_GET['m']):0;

        $list=Db::table('x1_user')->field('uid,name,avatar,phone')->where('uid','neq',$uid)->where('(name !="" or phone!="")');
        if($keywords){
            if(preg_match("/^1[34578]{1}\d{9}$/",$keywords)){
                $list=$list->where('phone','like',':phone')->bind(['phone'=>"%{$keywords}%"]);
            }else{
                $list=$list->where('name','like',':name')->bind(['name'=>"%{$keywords}%"]);
            }

        }
        if($m && $id){
            $list=$list->where('uid','gt',$id);
        }
        $list=$list->order('uid')->limit(0,20)->select();

        foreach($list as $k=>$v){
            $list[$k]['avatar']=$v['avatar']?$v['avatar']:'https://c.g56.cn/x9/user_im.png';
            $list[$k]['name']=$v['name']?$v['name']:$v['phone'];
        }

        echo json_encode(['err'=>0,'list'=>$list]);
    }

    public function select_concact(){
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid=$ses['uid'];
        $id=isset($_GET['id'])?intval($_GET['id']):0;
        $now=$_SERVER['REQUEST_TIME'];
        if($uid>$id){
            $min=$id;
            $max=$uid;
        }else{
            $min=$uid;
            $max=$id;
        }
        $qs=Db::query('select id from x1_msg_room where uid=? and muid=?',[$min,$max]);
        if($qs){
            $room_id=$qs[0]['id'];
        }else{
            $room_id=Db::table('x1_msg_room')->insertGetId(['uid'=>$min,'muid'=>$max,'time'=>$now,'state'=>'1','mstate'=>'1','last_msg'=>'']);
        }
        if($room_id){
            echo '{"err":0,"msg":"获取房间id成功","room_id":"'.$room_id.'"}';
        }else{
            echo '{"err":1,"msg":"获取房间id失败"}';
        }
    }


    public function curl($url, $method = 'get', $data = '')
    {
        $ch = curl_init();
        $header = ["Accept-Charset: utf-8"];
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
    }

    public function refresh()
    {
    }

    protected function tx_addr($loc)
    {
        $str = curl('https://apis.map.qq.com/ws/geocoder/v1/?key=BCJBZ-ZDIW4-R7QUD-XVMDH-JCKXE-VFBYX&output=json&poi_options=address_format=short;radius=1000;policy=4&location=' . $loc);
        // loger($str, 'kong');
        $rev = json_decode($str, true);
        if ($rev['status'] == 0) {
            return $rev['result'];
        } else {
            return null;
        }
    }


    public function xzb_auth()
    {
        $data = ['oid' => 1, 'uid' => 1];
        session('ses', $data);
        echo phpinfo();
    }


}